import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

import { deviceDetection, getConfig, responsiveStorageNameSpace, storageLocal } from '../utils'

export const useAppStore = defineStore('pure-app', () => {
  // state
  const sidebar = ref({
    opened:
      storageLocal().getItem<StorageConfigs>(`${responsiveStorageNameSpace()}layout`)
        ?.sidebarStatus ??
      getConfig().SidebarStatus ??
      false,
    withoutAnimation: false,
    isClickCollapse: false,
  })

  // 这里的layout用于监听容器拖拉后恢复对应的导航模式
  const layout = ref(
    storageLocal().getItem<StorageConfigs>(`${responsiveStorageNameSpace()}layout`)?.layout ??
      getConfig().Layout ??
      'vertical',
  )

  const device = ref(deviceDetection() ? 'mobile' : 'desktop')

  // 浏览器窗口的可视区域大小
  const viewportSize = ref({
    width: document.documentElement.clientWidth,
    height: document.documentElement.clientHeight,
  })

  // 作用于 src/views/components/draggable/index.vue 页面，当离开页面并不会销毁 new Swap()，sortablejs 官网也没有提供任何销毁的 api
  const sortSwap = ref(false)

  // getters
  const getSidebarStatus = computed(() => sidebar.value.opened)
  const getDevice = computed(() => device.value)
  const getViewportWidth = computed(() => viewportSize.value.width)
  const getViewportHeight = computed(() => viewportSize.value.height)

  // actions
  function TOGGLE_SIDEBAR(opened?: boolean, resize?: string) {
    const layoutConfig = storageLocal().getItem<StorageConfigs>(
      `${responsiveStorageNameSpace()}layout`,
    )
    if (opened && resize) {
      sidebar.value.withoutAnimation = true
      sidebar.value.opened = true
      layoutConfig.sidebarStatus = true
    } else if (!opened && resize) {
      sidebar.value.withoutAnimation = true
      sidebar.value.opened = false
      layoutConfig.sidebarStatus = false
    } else if (!opened && !resize) {
      sidebar.value.withoutAnimation = false
      sidebar.value.opened = !sidebar.value.opened
      sidebar.value.isClickCollapse = !sidebar.value.opened
      layoutConfig.sidebarStatus = sidebar.value.opened
    }
    storageLocal().setItem(`${responsiveStorageNameSpace()}layout`, layoutConfig)
  }

  async function toggleSideBar(opened?: boolean, resize?: string) {
    await TOGGLE_SIDEBAR(opened, resize)
  }

  function toggleDevice(deviceType: string) {
    device.value = deviceType
  }

  function setLayout(layoutType) {
    layout.value = layoutType
  }

  function setViewportSize(size) {
    viewportSize.value = size
  }

  function setSortSwap(val) {
    sortSwap.value = val
  }

  return {
    // state
    sidebar,
    layout,
    device,
    viewportSize,
    sortSwap,

    // getters
    getSidebarStatus,
    getDevice,
    getViewportWidth,
    getViewportHeight,

    // actions
    TOGGLE_SIDEBAR,
    toggleSideBar,
    toggleDevice,
    setLayout,
    setViewportSize,
    setSortSwap,
  }
})

export default useAppStore()
